
package com.idealighter.game.games.shuihu.handler;

import com.idealighter.game.core.annotation.ResMsgHandler;
import com.idealighter.game.dictionary.domain.RobotConfigDomain;
import com.idealighter.game.dictionary.domain.ShuihuRoomDomain;
import com.idealighter.game.gamehall.dto.MemInfo;
import com.idealighter.game.games.shuihu.ShuiHuPlayer;
import com.idealighter.game.games.shuihu.message.ReqExitTableMsg;
import com.idealighter.game.message.ModuleMsgIdConstant;
import com.idealighter.game.message.core.ResMessage;
import com.idealighter.game.robot.core.Player;
import com.idealighter.game.robot.handler.ResMessageHandler;
import com.idealighter.utils.code.RandCodeUtil;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@ResMsgHandler(ModuleMsgIdConstant.ShuiHu.BILL)
public class ResBillHandler implements ResMessageHandler {

  private static final Logger LOG = LoggerFactory.getLogger(ResBillHandler.class);


  @Override
  public void action(Player player, ResMessage message) {
    // ResBillMsg msg = (ResBillMsg)message;
    MemInfo member = player.member(player.playerId);

    // 校验玩家身上的钱换成的筹码是否足够(最小筹码*8 + 台费)
    if (member.getChips() < 1) {
      LOG.info("[水浒传]玩家[{}][{}]游戏中输光所有筹码", player.userName, player.playerId);
      player.delayLogout();
      return;
    }

    RobotConfigDomain robotCfg = player.configDomain;
    ShuihuRoomDomain roomDomain = ((ShuiHuPlayer) player).roomDomain;
    long maxGold = robotCfg.getMaxGold();
    // 超过最大携带金币需要退出房间
    if (convertGold(roomDomain, member.getChips()) > maxGold) {
      LOG.info("[水浒传]玩家[{}][{}]游戏中身上的金币超过最大携带金币", player.userName, player.playerId, maxGold);
      player.delayLogout();
      return;
    }

    // 超过最大游戏局数
    if (player.totalGameNum-- < 1) {
      LOG.info("[水浒传]玩家[{}][{}]游戏中超过总游戏局数退出游戏...", player.userName, player.playerId);
      player.delayLogout();
      return;
    }

    LOG.info("[水浒传]玩家[{}][{}]结算", player.userName, player.playerId);

    // 超过换桌局数
    if (player.tableGameNum-- < 1) {
      player.tableGameNum =
          RandCodeUtil.random(robotCfg.getTableGameLower(), robotCfg.getTableGameUpper());
      LOG.info("[水浒传]玩家[{}][{}]游戏中超过换桌局数换桌...", player.userName, player.playerId);
      player.sendMsg(new ReqExitTableMsg());
      return;
    }

    player.schedule(() -> ((ShuiHuPlayer) player).startShuiHu(), RandCodeUtil.random(10, 15),
        TimeUnit.SECONDS);
  }

  /**
   * 筹码换算金币.
   * 
   * @param roomDomain .
   * @param chips .
   */
  public long convertGold(ShuihuRoomDomain roomDomain, long chips) {
    return chips * roomDomain.getProportionGold() / roomDomain.getProportionChips();
  }
}
